package com.changhong.wlyspectrum.MainTestActivity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.changhong.wlyspectrum.NetWork.HttpMethods;
import com.changhong.wlyspectrum.R;
import com.changhong.wlyspectrum.utils.Attributes;
import com.changhong.wlyspectrum.utils.Detail;
import com.changhong.wlyspectrum.utils.MetaDataBean;
import com.changhong.wlyspectrum.utils.MyConfig;
import com.changhong.wlyspectrum.utils.PredictAttributeResponse;
import com.changhong.wlyspectrum.utils.RoundProgressBar;
import com.changhong.wlyspectrum.utils.SampleInfo;
import com.changhong.wlyspectrum.utils.ScioModel;
import com.changhong.wlyspectrum.utils.ScioModelImpl;
import com.google.gson.Gson;
import com.squareup.okhttp.Response;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Mr_tao
 * on 2017/3/9.
 */
public class TestAnalyseActivity extends Activity{
    private final static String TAG = "TestAnalyseActivity";
    private ImageView mBackIv;
    private Button mRecordBtn;
    private String device_id;
    private String user_id;
    private String token;
    private double[][] Tdata = new double[100][2];
    //private double[][] Tdata1 = new double[100][2];
    private double[][] Tdata2 = new double[100][2];
    private boolean HasData = true;
    private ListView mListView;
    private List<String> listKey = new ArrayList<String>();
    private List<Double> listValue = new ArrayList<Double>();
    private String collectionId;
    private String name;
    private String description;
    private JSONArray mJsonArray = null;
    //Map<String, Double> result = new HashMap<String, Double>();
    private List<PredictAttributeResponse> result = new ArrayList<PredictAttributeResponse>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_analyse_layout);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_test_analyse);

        InitData();
        InitUi();
    }

    private void InitData() {
        Intent intent = getIntent();
        collectionId = intent.getStringExtra("collectionId");
        Log.e(TAG,"collectionId----->" + collectionId);
        SharedPreferences mypref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        device_id = mypref.getString("device_id", "default");
        user_id = mypref.getString("user_id", "default");
        token = mypref.getString("token", "default");

        InputStream abpath = null;
        if(collectionId.compareTo("1") == 0){   //玉米蛋白粉
            abpath = TestAnalyseActivity.this.getClass().getClassLoader().getResourceAsStream("assets/scio.model1.json");
        }else if(collectionId.compareTo("2") == 0){  //五粮液
            abpath = TestAnalyseActivity.this.getClass().getClassLoader().getResourceAsStream("assets/scio.model2.json");
        }else if(collectionId.compareTo("14") == 0){  //糯米粉末
            abpath = TestAnalyseActivity.this.getClass().getClassLoader().getResourceAsStream("assets/scio.model14.json");
        }else{
            abpath = TestAnalyseActivity.this.getClass().getClassLoader().getResourceAsStream("assets/scio.model1.json");  //默认测试用
        }

        //Map<String, Double> result = new HashMap<String, Double>();
        ScioModelImpl scioModel = null;
        try {
            scioModel = new ScioModelImpl(abpath);
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (MyConfig.predictRequest.getId().compareTo("-1") != 0) {
            Log.e(TAG, "MyConfig.sampleBean.getId()----->" + MyConfig.predictRequest.getId());
            if(scioModel != null){
                result = scioModel.predict(MyConfig.predictRequest,collectionId);
            }else{
                Log.e(TAG, "scioModel is null");

            }

            /*for (Map.Entry<String, Double> entry : result.entrySet()) {
                listKey.add(entry.getKey());
                listValue.add(entry.getValue());
                //System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            }*/
        } else {
            HasData = false;
            Log.e(TAG, "No Data");
            Toast.makeText(getApplicationContext(), getString(R.string.todo_adjust), Toast.LENGTH_SHORT).show();
        }

        Tdata = MainTestActivity.Data;
        //Tdata1 = MainTestActivity.mData0;
        Tdata2 = MainTestActivity.mData1;
        GetCollectiodById();
    }


    private void InitUi() {
        mBackIv = (ImageView) findViewById(R.id.showresult2test);
        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mListView = (ListView)findViewById(R.id.myListView);

        MyAdapter mAdapter = new MyAdapter(TestAnalyseActivity.this);
        mListView.setAdapter(mAdapter);
       /* mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Log.e(TAG, "position" + arg2 + "onclick");
                Dialog dialog = new Dialog(TestAnalyseActivity.this,R.style.Dialog);
                View view1= LayoutInflater.from(TestAnalyseActivity.this).inflate(R.layout.new_analyse_list_item_item, null);
                dialog.setContentView(view1);
                dialog.setCanceledOnTouchOutside(true);
                *//*RoundProgressBar mRoundProgressBar1 = (RoundProgressBar) view1.findViewById(R.id.roundProgressBar1);
                TextView tv = (TextView)view1.findViewById(R.id.text1);
                float progress = 0;
                if((listValue.get(arg2)) < 0 || listValue.get(arg2) > 100){
                    Log.e(TAG, listValue.get(arg2) + "");
                    progress = 0;
                }else{
                    progress = listValue.get(arg2).floatValue();
                }
                mRoundProgressBar1.setProgress(progress);
                tv.setText(listKey.get(arg2));*//*
                TextView tv_name = (TextView)view1.findViewById(R.id.tv_name);
                TextView tv_value = (TextView)view1.findViewById(R.id.tv_value);
                TextView tv_lower = (TextView)view1.findViewById(R.id.tv_lower);
                TextView tv_upper = (TextView)view1.findViewById(R.id.tv_upper);
                TextView tv_unit = (TextView)view1.findViewById(R.id.tv_unit);

                tv_name.setText(getString(R.string.predict_name) + result.get(arg2).getName());
                tv_value.setText(getString(R.string.predict_value) + result.get(arg2).getValue());
                tv_lower.setText(getString(R.string.predict_lower) + result.get(arg2).getLower());
                tv_upper.setText(getString(R.string.predict_upper) + result.get(arg2).getUpper());
                tv_unit.setText(getString(R.string.predict_unit) + result.get(arg2).getUnit());

                dialog.show();
            }
        });*/
        mRecordBtn = (Button) findViewById(R.id.test_record_btn);
        mRecordBtn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(TestAnalyseActivity.this,
                        TestRecordActivity.class);
                intent.putExtra("collectionId",collectionId);
                startActivity(intent);
            }
        });

    }

    private Handler TestHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    List<Double> label = new ArrayList<Double>();
                    List<Double> series = new ArrayList<Double>();
                    List<Double> noLight = new ArrayList<Double>();
                    List<Double> baseLight = new ArrayList<Double>();
                    for (int i = 0; i < Tdata.length; i++) {
                        label.add(Tdata[i][0]);
                        series.add(Tdata[i][1]);
                        noLight.add(0.0);
                        baseLight.add(Tdata2[i][1]);
                    }
                    MetaDataBean metadata = new MetaDataBean();
                    if(collectionId.compareTo("1") == 0){
                        metadata.setName("铁骑力士智能快检");
                        metadata.setCollect("玉米蛋白粉分析");
                    }else if(collectionId.compareTo("2") == 0){
                        metadata.setName("五粮液智能快检");
                        metadata.setCollect("酒嶆分析");
                    }else{
                        metadata.setName("智能快检");
                        metadata.setCollect("样本分析");
                    }
                    SampleInfo sampleInfo = new SampleInfo();
                    sampleInfo.setSampleType("custom");
                    sampleInfo.setStart("1550");
                    sampleInfo.setStep("1850");
                    sampleInfo.setNumber("100");
                    metadata.setSampleInfo(sampleInfo);

                    metadata.setLabel(label);
                    metadata.setSeries(series);

                    Detail detail = new Detail();
                    detail.setNoLightSeries(noLight);
                    detail.setBaseLightSeries(baseLight);
                    metadata.setDetail(detail);

                    /*Attributes attributes = new Attributes();
                    attributes.setWater(mem_1 + "");
                    attributes.setStarch(mem_2 + "");
                    attributes.setAcidity(mem_3 + "");
                    attributes.setSugar(mem_4 + "");*/
                    HashMap<String,String> hashMap = new HashMap<String,String>();
                    /*for(int i = 0 ; i < mJsonArray.length();i++) {
                        try {
                            JSONObject info = (JSONObject)mJsonArray.get(i);
                            hashMap.put(info.getString("name"),"0");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }*/
                    for(int i = 0;i < result.size();i++){
                        hashMap.put(result.get(i).getName(),Double.toString(result.get(i).getValue()));
                    }
                    /*hashMap.put("water","0");
                    hashMap.put("starch","0");
                    hashMap.put("acidity","0");
                    hashMap.put("sugar","0");*/
                    metadata.setAttri(hashMap);

                    UpdateData(user_id,device_id,name,collectionId,description,"0",metadata);
                    break;
                case 1:
                    Toast.makeText(getApplicationContext(), R.string.update_success, Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    Toast.makeText(getApplicationContext(), R.string.update_fail, Toast.LENGTH_LONG).show();
                    break;
                case 3:
                    if(HasData){
                        TestHandler.sendMessage(Message.obtain(TestHandler, 0));
                    }
                    break;
                case 98:
                    Toast.makeText(getApplicationContext(), R.string.network_error, Toast.LENGTH_LONG).show();
                    break;
                case 99:
                    Toast.makeText(getApplicationContext(), R.string.service_error, Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };

    public class MyAdapter extends BaseAdapter {
        private LayoutInflater layoutInflater;
        private Context context;

        public MyAdapter(Context context){
            this.context=context;
            this.layoutInflater=LayoutInflater.from(context);
        }
        @Override
        public int getCount() {

            return result.size();
        }

        @Override
        public Object getItem(int position) {

            return result.get(position);
        }

        @Override
        public long getItemId(int position) {

            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;
            if(convertView == null){
                viewHolder = new ViewHolder();
                convertView=layoutInflater.inflate(R.layout.listview_item, null);
                viewHolder.tv = (TextView)convertView.findViewById(R.id.lv_item);
                viewHolder.tv1 = (TextView)convertView.findViewById(R.id.lv_text);
                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder)convertView.getTag();
            }

            Log.e(TAG,"result.get(position).getName():"+result.get(position).getName());
            viewHolder.tv.setText(result.get(position).getName().toString());
            if(((result.get(position).getValue()) > (result.get(position).getUpper())) || ((result.get(position).getValue()) < (result.get(position).getLower()))){
                viewHolder.tv1.setTextColor(getResources().getColor(R.color.red));
                //viewHolder.tv1.setText(Double.toString(result.get(position).getValue()));
            }else{
                viewHolder.tv1.setTextColor(getResources().getColor(R.color.black));
                //viewHolder.tv1.setText(Double.toString(result.get(position).getValue()));
            }
            //保留二位小数显示
            double mr = result.get(position).getValue().floatValue();
            NumberFormat nf = new DecimalFormat( "0.00");
            mr = Double.parseDouble(nf.format(mr));
            viewHolder.tv1.setText(""+mr);
            return convertView;
        }

        public final class ViewHolder{
            public TextView tv;
            public TextView tv1;
        }
    }

    private void UpdateData(final String userId, final String deviceId, final String name,final String collectionId,final String description, final String isSimple,final MetaDataBean metaDataBean){
        new Thread(){
            @Override
            public void run() {
                super.run();
                String mfirmwareVersion = "USBV1.0";
                String mappVersion = "1.0";
                String msoftVersion = "1.0.1";
                String mmodelVersion = "0.0.1";
                try{
                    Gson gson = new Gson();
                    String metadata = gson.toJson(metaDataBean);
                    Log.e(TAG,metadata);
                    Response response = HttpMethods.UpdateResponse("/scio/records/add",token,userId,deviceId,name,collectionId,description,isSimple,metadata,mfirmwareVersion,mappVersion,msoftVersion,mmodelVersion);
                    if(response.isSuccessful()){
                        String result = response.body().string();
                        Log.e(TAG,"result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        if (code.compareTo("0") == 0) {
                            TestHandler.sendMessage(Message.obtain(TestHandler, 1));
                        } else {
                            TestHandler.sendMessage(Message.obtain(TestHandler, 2));
                        }
                    }else{
                        TestHandler.sendMessage(Message.obtain(TestHandler, 98));
                    }
                } catch (IOException e) {
                    TestHandler.sendMessage(Message.obtain(TestHandler, 98));
                    e.printStackTrace();
                } catch (JSONException e) {
                    TestHandler.sendMessage(Message.obtain(TestHandler, 98));
                    e.printStackTrace();
                }
            }
        }.start();
    }

    private void GetCollectiodById(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                String path = "/collection/" + collectionId;
                try {
                    Response response = HttpMethods.TGetResponse(path,user_id,token);
                    if(response.isSuccessful()){
                        String result = response.body().string();
                        Log.e(TAG,"result----->" + result);
                        JSONObject jsonObject = new JSONObject(result);
                        String code = jsonObject.getString("code");
                        Log.e(TAG,"code----->" + code);
                        if(code.compareTo("0") == 0){
                            //JSONObject jsonobj = jsonObject.getJSONObject("jsonObj");
                            JSONArray jsonArray = new JSONArray(jsonObject.getString("jsonObj"));
                            JSONObject jsonobj = new JSONObject(jsonArray.getString(0));
                            name = jsonobj.getString("name");
                            collectionId = jsonobj.getString("collectionId");
                            description = jsonobj.getString("description");
                            mJsonArray = new JSONArray(jsonobj.getString("attributeTemplate"));
                            Log.e(TAG,name + " " + collectionId + " " + description);
                            TestHandler.sendMessage(Message.obtain(TestHandler, 3));
                        }else{
                            TestHandler.sendMessage(Message.obtain(TestHandler, 99));
                        }
                    }else{
                        TestHandler.sendMessage(Message.obtain(TestHandler, 98));
                    }
                } catch (IOException e) {
                    TestHandler.sendMessage(Message.obtain(TestHandler, 98));
                    e.printStackTrace();
                }catch (JSONException e){
                    TestHandler.sendMessage(Message.obtain(TestHandler, 98));
                    e.printStackTrace();
                }
            }
        }.start();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e(TAG,"onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e(TAG,"onPause");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e(TAG,"onDestroy");
    }
}
